package com.temp.controller.utils;

import com.temp.config.MinioConfig;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Component
@Slf4j
public class MinioUtil {

    @Autowired
    private MinioConfig minioConfig;

    @Value("${minio.filePrefix}")
    private String filePrefix;

    @Resource
    private MinioClient minioClient;

    /**
     * 检查存储桶是否存在
     * @param bucketName 存储桶名称
     * @return Boolean
     */
    public Boolean bucketExists(String bucketName) {
        try {
            return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            log.error("检查存储桶是否存在失败: {}", e.getMessage(), e);
            throw new RuntimeException("检查存储桶是否存在失败", e);
        }
    }

    /**
     * 创建存储桶
     * @param bucketName 存储桶名称
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            if (!bucketExists(bucketName)) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("创建存储桶失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建存储桶失败", e);
        }
    }

    /**
     * 删除存储桶
     * @param bucketName 存储桶名称
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            if (bucketExists(bucketName)) {
                minioClient.removeBucket(RemoveBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("删除存储桶失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除存储桶失败", e);
        }
    }

    /**
     * 获取所有存储桶列表
     * @return List<Bucket>
     */
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            log.error("获取存储桶列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取存储桶列表失败", e);
        }
    }

    /**
     * 文件上传
     * @param file 文件对象
     * @param bucketName 存储桶名称
     * @param path 自定义路径
     * @return 文件对象名称
     */
    public String upload(MultipartFile file, String bucketName, String path) {
        try {
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isBlank(originalFilename)) {
                throw new IllegalArgumentException("文件名称不能为空");
            }

            // 使用配置的桶或指定的桶
            String targetBucket = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();

            // 生成文件对象名称
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileExtension;
            String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM/dd"));
            String objectName = StringUtils.isNotBlank(path) ? path + fileName : datePath + "/" + fileName;

            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .bucket(targetBucket)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();

            minioClient.putObject(objectArgs);
            return objectName;
        } catch (Exception e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /**
     * 批量文件上传
     * @param files 文件列表
     * @param bucketName 存储桶名称
     * @param path 自定义路径
     * @return 文件名与URL映射
     */
    public Map<String, String> uploadBatch(MultipartFile[] files, String bucketName, String path) {
        Map<String, String> result = new HashMap<>();
        for (MultipartFile file : files) {
            String objectName = upload(file, bucketName, path);
            result.put(file.getOriginalFilename(), getFileUrl(bucketName, objectName));
        }
        return result;
    }

    /**
     * 获取文件预览URL
     * @param bucketName 存储桶名称
     * @param fileName 文件名称
     * @return 文件预览URL
     */
    public String preview(String bucketName, String fileName) {
        try {
            String targetBucket = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .bucket(targetBucket)
                            .object(fileName)
                            .method(Method.GET)
                            .build());
        } catch (Exception e) {
            log.error("获取文件预览URL失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取文件预览URL失败", e);
        }
    }

    /**
     * 文件下载
     * @param bucketName 存储桶名称
     * @param fileName 文件名称
     * @param attachment 是否作为附件下载
     * @param res HTTP响应
     */
    public void download(String bucketName, String fileName, boolean attachment, HttpServletResponse res) {
        try {
            String targetBucket = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();

            GetObjectArgs objectArgs = GetObjectArgs.builder()
                    .bucket(targetBucket)
                    .object(fileName)
                    .build();

            try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
                byte[] buf = new byte[1024];
                int len;
                try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
                    while ((len = response.read(buf)) != -1) {
                        os.write(buf, 0, len);
                    }
                    os.flush();
                    byte[] bytes = os.toByteArray();

                    res.setCharacterEncoding("utf-8");
                    res.setContentType(response.headers().get("Content-Type"));
                    if (attachment) {
                        res.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                    }

                    try (ServletOutputStream stream = res.getOutputStream()) {
                        stream.write(bytes);
                        stream.flush();
                    }
                }
            }
        } catch (Exception e) {
            log.error("文件下载失败: {}", e.getMessage(), e);
            throw new RuntimeException("文件下载失败", e);
        }
    }

    /**
     * 获取文件列表
     * @param bucketName 存储桶名称
     * @return 文件列表
     */
    public List<Item> listObjects(String bucketName) {
        try {
            String targetBucket = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            Iterable<Result<Item>> results = minioClient.listObjects(
                    ListObjectsArgs.builder().bucket(targetBucket).build());

            List<Item> items = new ArrayList<>();
            for (Result<Item> result : results) {
                items.add(result.get());
            }
            return items;
        } catch (Exception e) {
            log.error("获取文件列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取文件列表失败", e);
        }
    }

    /**
     * 删除文件
     * @param bucketName 存储桶名称
     * @param fileName 文件名称
     * @return Boolean
     */
    public boolean remove(String bucketName, String fileName) {
        try {
            String targetBucket = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(targetBucket)
                    .object(fileName)
                    .build());
            return true;
        } catch (Exception e) {
            log.error("删除文件失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除文件失败", e);
        }
    }

    /**
     * 获取文件信息
     * @param bucketName 存储桶名称
     * @param fileName 文件名称
     * @return 文件信息Map
     */
    public Map<String, Object> getFileInfo(String bucketName, String fileName) {
        try {
            String targetBucket = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            StatObjectResponse stat = minioClient.statObject(
                    StatObjectArgs.builder()
                            .bucket(targetBucket)
                            .object(fileName)
                            .build());

            Map<String, Object> info = new HashMap<>();
            info.put("bucket", stat.bucket());
            info.put("object", stat.object());
            info.put("size", stat.size());
            info.put("lastModified", stat.lastModified());
            info.put("contentType", stat.contentType());
            info.put("etag", stat.etag());

            return info;
        } catch (Exception e) {
            log.error("获取文件信息失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取文件信息失败", e);
        }
    }

    /**
     * 获取文件访问URL
     * @param bucketName 存储桶名称
     * @param objectName 文件对象名称
     * @return 文件URL
     */
    public String getFileUrl(String bucketName, String objectName) {
        String targetBucket = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
        return String.format("%s/%s/%s", filePrefix, targetBucket, objectName);
    }
}